const express = require('express');
const router = express.Router();
const RedisUtil = require("../util/RedisUtil");
const CacheKeyUtil = require("../util/CacheKeyUtil");
const DateUtil = require("../util/DateUtil");

router.get('/', async function (req, res, next) {

    const trendUserKeys = await RedisUtil.scan(CacheKeyUtil.trendKey.trendUser())
    let result = {};
    // 用户主体（公司、个人、组织）列表
    result.users = [];
    // 项目列表
    result.project = {};
    // 项目访问统计
    result.visitNum = {};
    let totalProject = 0;
    if (trendUserKeys) {
        for (let trendUserKey of trendUserKeys) {
            // 格式化用户名
            let username = trendUserKey.replace(CacheKeyUtil.trendKey.trendUser() + ':', '')
            result.users.push(username);

            // 获取用户下的项目集合
            const trendProjectKey = CacheKeyUtil.trendKey.trendProject(username);
            const projectKeys = await RedisUtil.scan(trendProjectKey);

            // 格式化项目名
            const projectNames = [];
            for (let projectKey of projectKeys) {
                let projectName = projectKey.replace(trendProjectKey + ':', '')
                projectNames.push(projectName)

                // 记录单个项目的访问次数
                result.visitNum[projectName] = await RedisUtil.get(CacheKeyUtil.trendKey.project(username, projectName))

            }
            result.project[username] = projectNames;

            // 累加总项目数
            totalProject += projectNames.length
        }
    }
    result.totalProject = totalProject
    result.totalUser = trendUserKeys.length
    res.render('trend', result);
});


router.get('/project/chart/:owner/:repo', async function (req, res, next) {
    // 仓库所有者
    const owner = req.params.owner
    // 仓库名
    const repo = req.params.repo

    const projectUsageTimeKey = CacheKeyUtil.trendKey.usageTime(owner, repo)
    let usageTimeList = await RedisUtil.smembers(projectUsageTimeKey);
    let xAxisData = [];
    let seriesData = [];
    if (usageTimeList) {
        //定义一个比较器
        function  compare( propertyName) {
            return  function( object1,  object2) {
                var value1  = object1[propertyName];
                var value2  = object2[propertyName];
                if (value2  < value1) {
                    return  1;
                }  else  if (value2  > value1) {
                    return  - 1;
                }  else {
                    return  0;
                }
            }
        }
        usageTimeList = usageTimeList.sort(compare( "startTime"))

        usageTimeList.forEach(function (item) {
            const startTime = item.startTime;
            const endTime = item.endTime;
            const usageTime = item.usageTime;
            xAxisData.push(DateUtil.formatDateTime(startTime, 'YYYY-MM-DD HH:mm:ss'))
            seriesData.push(usageTime)
        })
        xAxisData = xAxisData.length > 100 ? xAxisData.slice(xAxisData.length - 100) : xAxisData
        seriesData = seriesData.length > 100 ? seriesData.slice(seriesData.length - 100) : seriesData
    }

    res.json({
        xAxisData: xAxisData,
        seriesData: seriesData,
    });
})

module.exports = router;
